/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.propertyInfo;

import com.inspur.edp.caf.generator.baseInfo.AnnotationInfo;
import com.inspur.edp.caf.generator.baseInfo.PropertyGenerateInfo;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.property.ClassPropertyGenerator;
import com.inspur.edp.caf.generator.utils.ExpressionUtils;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.ElementDefaultVauleType;
import com.inspur.edp.cef.designtime.api.element.EnumIndexType;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.cef.designtime.api.element.GspEnumValue;
import com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.dataTypeInfo.DataTypeInfoGeneratorContext;
import com.inspur.edp.cef.generator.overall.GenUtils;
import com.inspur.edp.cef.generator.overall.Utils;
import com.inspur.edp.cef.spi.entity.DefaultValueType;
import com.inspur.edp.cef.spi.entity.PropertyDefaultValue;
import lombok.var;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

public class DefaultValueGenerator extends ClassPropertyGenerator {
  private IGspCommonField field;
  private DataTypeInfoGeneratorContext parentContext;
  public DefaultValueGenerator(IGspCommonField field, DataTypeInfoGeneratorContext parentContext) {
    this.field = field;
    this.parentContext = parentContext;
  }

  @Override
  protected TypeInfo getPropertyType() {
    return new TypeInfo(PropertyDefaultValue.class);
  }

  @Override
  protected String getFieldName() {
    return "private" + getPropertyName();
  }

  @Override
  protected String getPropertyName() {
    return "DefaultValue";
  }

  @Override
  protected java.util.ArrayList<AnnotationInfo> getGetterAttributeList() {
    return Utils.buildOverrideAnnotation();
  }

  @Override
  protected ArrayList<ModifierKeyword> getGetterAccessModifier() {
    return new ArrayList<ModifierKeyword>(
        Arrays.asList(new ModifierKeyword[] {ModifierKeyword.PUBLIC_KEYWORD}));
  }

  @Override
  protected ArrayList<ModifierKeyword> getSetterAccessModifier() {
    return null;
  }

  @Override
  protected Block buildGetMethodBody() {
    Block rez = ast.newBlock();
    if (field.getDefaultValueType() == ElementDefaultVauleType.Vaule) {
      rez.statements().add(getRealValueStatement());
      rez.statements().add(createDefaultInfo());
    }
    else if (field.getDefaultValueType() == ElementDefaultVauleType.Expression){
      rez.statements().add(getExpressionValueStatement());
      rez.statements().add(createExpressionDefaultInfo());
    }
    return rez;
  }

  private Statement createDefaultInfo() {

    ClassInstanceCreation  creationExpr = ast.newClassInstanceCreation();
    creationExpr.setType(new TypeInfo(PropertyDefaultValue.class).getType(ast,parentContext.getDataTypeInterfaceCtx().getApiGenContext()));
//    ast.newSimpleType(ast.newSimpleName(PropertyDefaultValue.class.getName()))
    StringLiteral valueArg = ast.newStringLiteral();
    valueArg.setLiteralValue(field.getDefaultValue());
    creationExpr.arguments().add(valueArg);

    var realValueArg = ast.newSimpleName("realValue");
//    realValueArg.setName(ast.newSimpleName("realValue"));
    creationExpr.arguments().add(realValueArg);

    QualifiedName valueTypeArg = ast.newQualifiedName(ast.newName(DefaultValueType.class.getName()), ast.newSimpleName("Value"));
    creationExpr.arguments().add(valueTypeArg);

    var returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(creationExpr);
    return returnStatement;
  }

  private Statement createExpressionDefaultInfo() {

    ClassInstanceCreation  creationExpr = ast.newClassInstanceCreation();
    creationExpr.setType(new TypeInfo(PropertyDefaultValue.class).getType(ast,parentContext.getDataTypeInterfaceCtx().getApiGenContext()));
//    ast.newSimpleType(ast.newSimpleName(PropertyDefaultValue.class.getName()))
    StringLiteral valueArg = ast.newStringLiteral();
    valueArg.setLiteralValue(field.getDefaultValue());
    creationExpr.arguments().add(valueArg);

    var realValueArg = ast.newSimpleName("realValue");
//    realValueArg.setName(ast.newSimpleName("realValue"));
    creationExpr.arguments().add(realValueArg);

    QualifiedName valueTypeArg = ast.newQualifiedName(ast.newName(DefaultValueType.class.getName()), ast.newSimpleName("Expression"));
    creationExpr.arguments().add(valueTypeArg);

    var returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(creationExpr);
    return returnStatement;
  }

  private Statement getRealValueStatement() {
    Expression invocation = getRealValueInvocation();

    TypeInfo fieldType ;
    if(field.getObjectType() == GspElementObjectType.Enum)
      fieldType = new TypeInfo(String.class);
    else
      fieldType= Utils.getNativeType(field, parentContext.getDataTypeInterfaceCtx().getApiGenContext().getCefGenContext());

    var frag = ast.newVariableDeclarationFragment();
    frag.setName(ast.newSimpleName("realValue"));
    frag.setInitializer(invocation);
    var statement = ast.newVariableDeclarationStatement(frag);
    statement.setType(fieldType.getType(ast, parentContext.getDataTypeInterfaceCtx().getApiGenContext()));
    return statement;
  }

  private Statement getExpressionValueStatement() {
    Expression invocation = getDefault();

    var frag = ast.newVariableDeclarationFragment();
    frag.setName(ast.newSimpleName("realValue"));
    frag.setInitializer(invocation);
    var statement = ast.newVariableDeclarationStatement(frag);
    statement.setType(ast.newSimpleType(ast.newSimpleName("String")));
    return statement;
  }

  private Expression getRealValueInvocation() {
    Expression convertInvocation;
    if (field.getObjectType() == GspElementObjectType.Enum){
      return getEnumValue();
    }
    if (field.getObjectType() != GspElementObjectType.None ) {
      return getDefault();
    }
    switch (field.getMDataType()) {
      case Integer:
        convertInvocation = getConvertIntSyntax();
        break;
      case Decimal:
        convertInvocation = getConvertDecimalSyntax();
        break;
      case Boolean:
        convertInvocation = getConvertBoolSyntax();
        break;
      case Date:
      case DateTime:
        convertInvocation = getConvertDateSyntax();
        break;
      default:
        return getDefault();
    }

    return convertInvocation;
  }

  private Expression getEnumValue(){
    var enums = field.getContainEnumValues();
    if(enums == null)
      throw new RuntimeException("字段"+field.getLabelID()+"上没有设置枚举项");
    String defaultValue = field.getDefaultValue();
    String realDefaultValue =null;
    boolean indexTypeString = field.getEnumIndexType() == EnumIndexType.String;
    for(var enumInfo :enums){
      if(indexTypeString)
        realDefaultValue = getEnumDefaultValue(enumInfo.getStringIndex(), defaultValue, enumInfo);
      else
        realDefaultValue = getEnumDefaultValue(String.valueOf(enumInfo.getIndex()), defaultValue, enumInfo);

      if(realDefaultValue != null)
        break;
    }

    if(realDefaultValue == null)
      realDefaultValue = defaultValue;

    return ExpressionUtils.getStringLiteral(ast, realDefaultValue);
  }

  private String getEnumDefaultValue(String index, String defaultValue, GspEnumValue enumInfo){
    if(index.equals(defaultValue))
      return enumInfo.getValue();
    return null;
  }

  private Expression getDefault() {
    return ExpressionUtils.getStringLiteral(ast, field.getDefaultValue());

  }

  private MethodInvocation getConvertIntSyntax() {
//Integer.parseInt
    var invocation = ExpressionUtils.getMethodInvocation(ast, "Integer","parseInt");
    addImport("java.lang.Integer");
    invocation.arguments().add(ExpressionUtils.getStringLiteral(ast, field.getDefaultValue()));
    return invocation;
  }

  private MethodInvocation getConvertBoolSyntax() {
    var invocation = ExpressionUtils.getMethodInvocation(ast, "Boolean","parseBoolean");
    invocation.arguments().add(ExpressionUtils.getStringLiteral(ast, field.getDefaultValue()));
    return invocation;
  }

  private Expression getConvertDecimalSyntax() {
    var invocation = GenUtils.buildClassInstantiation(ast, BigDecimal.class);
    invocation.arguments().add(ExpressionUtils.getStringLiteral(ast, field.getDefaultValue()));
    return invocation;
  }

  private Expression getConvertDateSyntax() {
    return ast.newNullLiteral();
//    var invocation = GenUtils.buildClassInstantiation(ast, Date.class);
//    invocation.arguments().add(ExpressionUtils.getStringLiteral(ast, field.getDefaultValue()));
//    return invocation;
  }

  @Override
  protected boolean hasSetMethod() {
    return false;
  }
}
